import { Request, Response, NextFunction } from "express";
import { HttpError } from "../utils/httpError";
import { ErrorCode } from "../constants/errorCode";
import { ZodError } from "zod";
import { logger } from "../utils/logger";
import { zhMessages } from "../constants/errorMessage.zh";
import { enMessages } from "../constants/errorMessage.en";

const getMessage = (code: ErrorCode, lang: "zh" | "en") => {
  return lang === "en" ? enMessages[code] : zhMessages[code];
};
export const errorHandler = (
  err: any,
  req: Request,
  res: Response,
  next: NextFunction
) => {
  console.log(err)
  const lang = (req as any).lang || "zh";
  const ErrMessage = getMessage(err.code, lang);
  logger.error(`[${req.method}] ${req.originalUrl} - ${err.customMsg || ErrMessage}`);
  if (err instanceof HttpError) {
    return res.status(err.status).json({
      code: err.code,
      message: err.customMsg || ErrMessage,
      data: null,
    });
  }

  if (err instanceof ZodError) {
    const formatted = err.format();
    const msg = Object.entries(formatted)
      .filter(([key]) => key !== "_errors")
      .map(([key, val]) => `${key}: ${(val as any)._errors?.[0] || "Invalid"}`)
      .join(", ");
    return res.status(400).json({
      code: ErrorCode.VALIDATION,
      message: msg || getMessage(ErrorCode.VALIDATION, lang),
      data: null,
    });
  }

  return res.status(500).json({
    code: ErrorCode.SERVER_ERROR,
    message: getMessage(ErrorCode.SERVER_ERROR, lang),
    error: process.env.NODE_ENV === "development" ? err.message : undefined,
    data: null,
  });
};
